import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import '../values/constants.dart';

/// 应用包信息服务
/// 负责获取和管理应用的版本信息、包名等元数据
class PackageInfoService extends GetxService {
  static PackageInfoService get to => Get.find<PackageInfoService>();
  
  // 响应式变量
  final _appName = ''.obs;
  final _packageName = ''.obs;
  final _version = ''.obs;
  final _buildNumber = ''.obs;
  final _isInitialized = false.obs;
  
  // 私有变量存储PackageInfo实例
  PackageInfo? _packageInfo;
  
  // Getters - 响应式访问
  String get appName => _appName.value;
  String get packageName => _packageName.value;
  String get version => _version.value;
  String get buildNumber => _buildNumber.value;
  bool get isInitialized => _isInitialized.value;
  
  // Getters - 响应式Observable
  RxString get appNameRx => _appName;
  RxString get packageNameRx => _packageName;
  RxString get versionRx => _version;
  RxString get buildNumberRx => _buildNumber;
  RxBool get isInitializedRx => _isInitialized;
  
  @override
  Future<void> onInit() async {
    super.onInit();
    debugPrint('🔧 PackageInfoService 初始化开始...');
    
    try {
      await _loadPackageInfo();
      debugPrint('✅ PackageInfoService 初始化完成');
    } catch (e) {
      debugPrint('❌ PackageInfoService 初始化失败: $e');
      rethrow;
    }
  }
  
  /// 加载应用包信息
  Future<void> _loadPackageInfo() async {
    try {
      debugPrint('📦 正在获取应用包信息...');
      
      // 获取包信息
      _packageInfo = await PackageInfo.fromPlatform();
      
      // 更新响应式变量
      _appName.value = _packageInfo?.appName ?? Constants.unknownAppName;
      _packageName.value = _packageInfo?.packageName ?? Constants.defaultPackageName;
      _version.value = _packageInfo?.version ?? Constants.defaultVersion;
      _buildNumber.value = _packageInfo?.buildNumber ?? Constants.defaultBuildNumber;
      
      // 标记为已初始化
      _isInitialized.value = true;
      
      // 打印包信息（仅调试模式）
      if (kDebugMode) {
        _printPackageInfo();
      }
      
      debugPrint('✅ 应用包信息加载完成');
    } catch (e) {
      debugPrint('❌ 获取应用包信息失败: $e');
      
      // 设置默认值
      _setDefaultValues();
      _isInitialized.value = false;
      
      rethrow;
    }
  }
  
  /// 设置默认值（当获取包信息失败时）
  void _setDefaultValues() {
    _appName.value = Constants.standardProjectAppName;
    _packageName.value = 'com.example.flutter_init';
    _version.value = Constants.defaultVersion;
    _buildNumber.value = Constants.defaultBuildNumber;
  }
  
  /// 打印包信息详情（调试用）
  void _printPackageInfo() {
    debugPrint('==================== 应用包信息 ====================');
    debugPrint('应用名称: ${_appName.value}');
    debugPrint('包名: ${_packageName.value}');
    debugPrint('版本号: ${_version.value}');
    debugPrint('构建号: ${_buildNumber.value}');
    debugPrint('================================================');
  }
  
  /// 重新加载包信息
  Future<void> reload() async {
    debugPrint('🔄 重新加载应用包信息...');
    
    try {
      await _loadPackageInfo();
      debugPrint('✅ 应用包信息重新加载完成');
    } catch (e) {
      debugPrint('❌ 重新加载应用包信息失败: $e');
      rethrow;
    }
  }
  
  /// 获取完整的版本信息字符串
  String get fullVersion => '${_version.value}+${_buildNumber.value}';
  
  /// 获取应用信息摘要
  Map<String, dynamic> getAppInfoSummary() {
    return {
      'appName': _appName.value,
      'packageName': _packageName.value,
      'version': _version.value,
      'buildNumber': _buildNumber.value,
      'fullVersion': fullVersion,
      'isInitialized': _isInitialized.value,
    };
  }
  
  /// 检查是否为调试版本（通常构建号包含debug标识）
  bool get isDebugBuild => _buildNumber.value.toLowerCase().contains('debug');
  
  /// 检查是否为发布版本
  bool get isReleaseBuild => !isDebugBuild;
  
  /// 获取应用显示名称（用于UI显示）
  String get displayName => _appName.value.isEmpty ? Constants.defaultAppName : _appName.value;
  
  /// 获取版本显示文本（用于UI显示）
  String get versionText => 'v${_version.value}';
  
  /// 获取详细版本显示文本
  String get detailedVersionText => 'v${_version.value} (${_buildNumber.value})';
  
  @override
  void onClose() {
    debugPrint('🧹 PackageInfoService 正在清理...');
    _packageInfo = null;
    super.onClose();
  }
}
